<template>
  <div class="login-container">
    <el-card class="login-card">
      <h2 class="login-title">系统登录</h2>
      <el-form ref="loginFormRef" :model="loginForm" :rules="loginRules" label-position="top">
        <el-form-item label="用户名" prop="username">
          <el-input
            v-model="loginForm.username"
            placeholder="请输入用户名"
            prefix-icon="User"
            clearable
            @keyup.enter="handleLogin"
            style="width: 500px"
          />
        </el-form-item>
        <el-form-item label="密码" prop="password">
          <el-input
            v-model="loginForm.password"
            placeholder="请输入密码"
            prefix-icon="Lock"
            type="password"
            show-password
            clearable
            @keyup.enter="handleLogin"
            style="width: 500px"
          />
        </el-form-item>
        <el-form-item label="验证码" prop="captcha">
          <div style="display: flex; width: 100%; justify-content: space-between; align-items: center">
            <el-input
              style="width: 240px"
              v-model="loginForm.captcha"
              placeholder="请输入验证码"
              clearable
              @keyup.enter="handleLogin"
            />
            <!-- 使用 img 标签显示验证码 -->
            <img :src="captchaImg?.data" @click="generateCaptcha" alt="验证码" style="cursor: pointer" />
          </div>
        </el-form-item>
        <el-form-item>
          <div class="form-actions">
            <el-checkbox v-model="loginForm.rememberMe">记住我</el-checkbox>
            <el-link type="primary" @click="goToRegister">没有账号？前往注册</el-link>
          </div>
          <el-button type="primary" :loading="loading" class="login-button" @click="handleLogin"> 登录 </el-button>
        </el-form-item>
      </el-form>
    </el-card>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from "vue";
import { useRouter } from "vue-router";
import { ElMessage } from "element-plus";
import { login } from "@/api/auth";
import { useUserStore } from "@/stores/user";
import { validatePasswordComplexity } from "@/utils/validators";
import { setToken } from "@/utils/auth";
import CaptchaUtil from "@/utils/captcha";
import { getUserInfo } from "@/api/user";

const router = useRouter();
const userStore = useUserStore();

const loginFormRef = ref(null);
const loading = ref(false);
// 验证码图片数据
const captchaImg = ref("");

// 登录表单数据
const loginForm = reactive({
  username: "",
  password: "",
  captcha: "",
  rememberMe: false,
});

const validateCaptcha = (rule, value, callback) => {
  if (!value) {
    return callback(new Error("请输入验证码"));
  }
  // 只允许字母数字
  if (!CaptchaUtil.verify(value, captchaImg.value.text)) {
    callback(new Error("验证码错误"));
  } else {
    callback();
  }
};

// 表单验证规则
const loginRules = {
  username: [
    { required: true, message: "请输入用户名", trigger: "blur" },
    { min: 3, max: 20, message: "用户名长度应在3-20个字符之间", trigger: "blur" },
  ],
  password: [
    { required: true, message: "请输入密码", trigger: "blur" },
    { validator: validatePasswordComplexity, trigger: "blur" },
  ],
  captcha: [
    { required: true, message: "请输入验证码", trigger: "blur" },
    { min: 4, max: 4, message: "验证码长度为4个字符", trigger: "blur" },
    { validator: validateCaptcha, trigger: "blur" },
  ],
};

// 生成普通验证码
const generateCaptcha = () => {
  captchaImg.value = CaptchaUtil.generate({
    width: 100,
    height: 40,
    charLength: 4,
  });
};

onMounted(() => {
  generateCaptcha();
});

// 处理登录
const handleLogin = async () => {
  if (!loginFormRef.value) return;

  await loginFormRef.value.validate(async (valid) => {
    if (!valid) return;

    loading.value = true;
    try {
      const res = await login(loginForm);
      if (res.success) {
        ElMessage.success("登录成功");

        // 存储token和用户信息
        const token = res.data.token;
        // 设置权限列表
        userStore.setPermissions(res.data.permissions);

        // 保存token到localStorage
        setToken(token);

        const getUserResponse = await getUserInfo();
        let userInfo = null;
        if (getUserResponse.success) {
          // 只保存用户信息到store，token只保存在localStorage
          userInfo = getUserResponse.data;
          userStore.setUserInfo(userInfo);
        }

        // 如果选择了记住我，则将用户基本信息保存到localStorage
        if (loginForm.rememberMe && userInfo) {
          localStorage.setItem("userInfo", JSON.stringify(userInfo));
        }

        // 跳转到首页
        router.push("/");
      }
    } catch (error) {
      console.error("登录出错：", error);
    } finally {
      loading.value = false;
    }
  });
};

// 跳转到注册页
const goToRegister = () => {
  router.push("/register");
};

// 如果记住密码，则自动填充
onMounted(() => {
  const userInfoStr = localStorage.getItem("userInfo");
  if (userInfoStr) {
    try {
      const userInfo = JSON.parse(userInfoStr);
      loginForm.username = userInfo.username || "";
      rememberMe.value = true;
    } catch (e) {
      console.error("解析用户信息出错：", e);
    }
  }
});
</script>

<style scoped>
.login-container {
  display: flex;
  justify-content: center;
  align-items: center;
  min-height: 100vh;
  background: linear-gradient(135deg, #f5f7fa 0%, #c3cfe2 100%);
}

.login-card {
  width: 400px;
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.login-title {
  text-align: center;
  margin-bottom: 20px;
  color: #303133;
}

.form-actions {
  display: flex;
  justify-content: space-between;
  margin-bottom: 15px;
}

.login-button {
  width: 100%;
  padding: 12px 0;
  font-size: 16px;
}
</style>
